<template>
  <div v-loading="tableLoading" class="app-container">
    <el-row :gutter="15">
      <el-col :span="16">
        <div class="search-box">
          <div class="search-form">
            <el-form ref="searchForm" size="small" :inline="true" :model="formFilter">
              <el-form-item label="编号" prop="code">
                <el-input v-model="formFilter.code" />
              </el-form-item>
              <el-form-item label="名称" prop="name">
                <el-input v-model="formFilter.name" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" @click="onSearch">查询</el-button>
                <el-button icon="el-icon-remove-outline" title="重置" @click="resetSearchForm" />
              </el-form-item>
            </el-form>
          </div>
          <div class="toolbar-box">
            <el-button type="primary" icon="el-icon-circle-plus" @click="add">新增</el-button>
            <el-button type="success" icon="el-icon-s-custom" @click="showUsers">有此角色的用户...</el-button>
          </div>
        </div>

        <el-table
          ref="simpleTable"
          stripe
          highlight-current-row
          :data="tableData"
          border
          class="table"
          @current-change="handleCurrentChange"
        >
          <el-table-column prop="code" label="编号" />
          <el-table-column prop="name" label="名称" />
          <el-table-column prop="isSystem" label="系统角色">
            <template slot-scope="scope">
              <span>{{ scope.row.isSystem |booleanFormat }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" width="120" />
          <el-table-column label="操作" width="160" align="left">
            <template slot-scope="scope">
              <el-button v-if="!scope.row.isSystem" type="text" icon="el-icon-edit" @click="handleEdit(scope.row.id)">编辑</el-button>
              <el-button
                v-if="!scope.row.isSystem"
                type="text"
                icon="el-icon-delete"
                class="red"
                @click="handleDelete(scope.row.id,scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
      <el-col :span="8">
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <div class="item">
              <el-tooltip effect="dark" content="选择所选角色的权限" placement="top">
                <span class="role-span">角色权限</span>
              </el-tooltip>
              <span v-if="currentRow" style="color:#ffcc33;font-size:16px;font-weight:600;">（{{ currentRow.name }}）</span>
            </div>
            <el-button
              :disabled="disSavePerm"
              icon="el-icon-check"
              style="float: right; "
              size="medium"
              type="primary"
              @click="savePermission"
            >保存</el-button>
          </div>
          <el-tree
            ref="permTree"
            :data="treeData"
            node-key="id"
            show-checkbox
            highlight-current
            :props="defaultProps"
            default-expand-all
            :expand-on-click-node="false"
          />
        </el-card>
      </el-col>
    </el-row>
    <!--表单组件-->
    <eForm ref="eform" />
    <eShow ref="eshow" />
  </div>
</template>

<script>
import { findRoles, deleteRole, getPermissions, updatePermission, getPermissionTree } from '@/api/role'
import eForm from './form'
import eShow from './show'
export default {
  name: 'RoleManager',
  components: { eForm, eShow },
  data() {
    return {
      tableLoading: true,
      disSavePerm: true,
      treeData: [],
      currentRow: null,
      permissions: [],
      tableData: [],
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      formFilter: {
        code: null,
        name: null
      }
    }
  },
  mounted() {
    // permission-----
    this.initPermission()
    this.getList()
  },
  methods: {
    initPermission() {
      getPermissionTree().then(data => {
        this.treeData = data
      }).catch(err => {
        this.$message.error(err.message)
      })
    },
    // 获取数据
    getList() {
      this.currentRow = null
      this.tableLoading = true
      const param = {}
      this.copyNotBlankField(this.formFilter, param)

      findRoles(param)
        .then(data => {
          this.tableLoading = false
          this.tableData = data
        })
        .catch(e => {
          this.tableLoading = false
          this.$message.error('查询出错')
        })
    },
    onSearch() {
      this.getList()
    },
    resetSearchForm() {
      this.$refs['searchForm'].resetFields()
    },
    handleEdit(id) {
      this.$refs.eform.edit(id)
    },
    handleDelete(id, row) {
      this.$confirm('此操作将删除[' + row.name + '], 是否继续?', '确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.doDelete(id)
        })
    },
    doDelete(id) {
      this.tableLoading = true
      deleteRole(id)
        .then(res => {
          this.tableLoading = false
          this.getList()
        })
        .catch(e => {
          this.tableLoading = false
          this.$message.error('删除出错！' + e.message ? e.message : '')
        })
    },
    add() {
      this.$refs.eform.add()
    },
    handleCurrentChange(row) {
      // 清空权限的选中
      this.$refs.permTree.setCheckedKeys([])
      if (!row) { // form.refresh
        return
      }
      this.currentRow = row

      this.disSavePerm = false

      // 取得角色权限
      this.tableLoading = true
      getPermissions(this.currentRow.id).then(data => {
        // 只设置leaf为 checked  --
        const checks = []
        for (let j = 0, len = data.length; j < len; j++) {
          if (this.$refs.permTree.getNode(data[j]).isLeaf) {
            checks.push(data[j])
          }
        }
        this.$refs.permTree.setCheckedKeys(checks)
        this.tableLoading = false
      }).catch(err => {
        this.disSavePerm = true
        this.tableLoading = false
        this.$message.error(err.message)
      })
    },
    savePermission() {
      this.tableLoading = true
      const keys = this.$refs.permTree.getCheckedKeys().concat(this.$refs.permTree.getHalfCheckedKeys())
      updatePermission(this.currentRow.id, keys)
        .then(res => {
          this.tableLoading = false
        })
        .catch(e => {
          this.tableLoading = false
          this.$message.error('设置角色权限出错！' + e.message ? e.message : '')
        })
    },
    showUsers() {
      if (this.currentRow) {
        this.$refs.eshow.show(this.currentRow)
      } else {
        this.$message.info('请先点击列表，选择一个角色。')
      }
    }

  }
}
</script>
